<script>
import config from './config'
import {getToken, setToken, setUpdateInfo} from "./utils/auth";
import {clearFileContent, readFile} from "./utils/storageFile";
import {postAction} from "./utils/action";
import appUpgrade from "./utils/AppUpgrade";

export default {
  onLaunch: function () {
    this.initApp()
  },
  methods: {
    // 初始化应用
    initApp() {
      // 全局挂载 Promise 控制器
      this.globalData.$onLaunched = new Promise(resolve => {
        this.globalData.$isResolve = resolve;
      });
      // 初始化应用配置
      this.initConfig()
      // 检查用户登录状态
      this.checkLogin()
      //  检查系统更新
      this.upApp()
    },
    initConfig() {
      this.globalData.config = config
    },
    async checkLogin() {
      const tokenData = await readFile();
      if (tokenData) {
        this.loginSuccess(tokenData.data)
      }
      // if (!getToken()) {
      //   this.$tab.reLaunch('/pages/login')
      // }
    },
    async upApp() {
      const updateInfo = await appUpgrade.checkVersion()
      setUpdateInfo(updateInfo)
      this.globalData.$isResolve(); // 通知同步完成
    },
    loginSuccess(res) {
      setToken(res.result.token)
      this.$store.state.user.token = res.result.token
      this.$store.state.user.avatar = (res.result.userInfo == null || res.result.userInfo.avatar == "" || res.result.userInfo.avatar == null) ? require("@/static/img/other/upload.png") : res.result.userInfo.avatar
      this.$store.state.user.roles = res.result.userInfo.staffType
      // this.$store.state.user.permissions = res.result.userInfo.name
      this.$store.state.user.name = res.result.userInfo.realname
      this.$store.state.user.info = res.result.userInfo
      postAction("sys/checkLogin").then(res => {
        if (res.success) {
          // 设置用户信息
          uni.reLaunch({
            url: '/pages/index'
          })
        } else {
          clearFileContent() //清空
        }
      })
    }
  }
}
</script>

<style lang="scss">
@import '@/static/scss/index.scss'
</style>
<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
